package klok;

import javax.swing.*;
import java.awt.*;

public class KlokPanel extends JPanel {
	public static final int KLOKSTRAAL = 100;
	private static final int clockDiameter = KLOKSTRAAL * 2;
	private static final double CLOCKPARTS = 30.0;
	private static final int secLijnLengte = (int) (0.98 * KLOKSTRAAL);
	private static final int minLijnLengte = (int) (0.95 * KLOKSTRAAL);
	private static final int uurLijnLengte = (int) (0.60 * KLOKSTRAAL);
	private static final int digitPosX = (int) (KLOKSTRAAL * 0.8);
	private static final int initialPos = KLOKSTRAAL;
	private static final int digitPosY = (int) (2.2 * KLOKSTRAAL);
	private int uur;
	private int minuut;
	private int seconde;
	private int[] alarm;
	private boolean alarmSetOff;

	public KlokPanel(int time[]) {
		uur = time[0];
		minuut = time[1];
		seconde = time[2];
		setSize(clockDiameter, clockDiameter);
	}

	public void paintComponent(Graphics g) {
		super.paintComponent(g);
		drawOval(g);
		drawLines(g, seconde, minuut, uur);
		drawDigits(g);
	}

	private void drawOval(Graphics g) {
		g.setColor(Color.white);
		g.fillOval(0, 0, clockDiameter, clockDiameter);
		g.setColor(Color.black);
		g.drawOval(0, 0, clockDiameter, clockDiameter);
	}

	private void drawLines(Graphics g, int seconde, int minuut, int uur) {
		drawSecAndMinLine(g, seconde, secLijnLengte);
		drawSecAndMinLine(g, minuut, minLijnLengte);
		drawHourLine(g, uur);
	}

	private void drawSecAndMinLine(Graphics g, int time, int lineLength) {
		g.drawLine(
				initialPos,
				initialPos,
				(int) (initialPos + lineLength
						* Math.sin(time / CLOCKPARTS * Math.PI)),
				(int) (initialPos - lineLength
						* Math.cos(time / CLOCKPARTS * Math.PI)));
	}

	private void drawHourLine(Graphics g, int time) {
		g.drawLine(
				initialPos,
				initialPos,
				(int) (initialPos + uurLijnLengte
						* Math.sin((60 * uur + minuut) / (CLOCKPARTS * 12)
								* Math.PI)),
				(int) (initialPos - uurLijnLengte
						* Math.cos((60 * uur + minuut) / (CLOCKPARTS * 12)
								* Math.PI)));
	}

	private void drawDigits(Graphics g) {
		if (alarmSetOff) {
			g.setColor(Color.red);
			g.drawString("Alarm was set off at " + alarm[0] + " " + alarm[1]
					+ " " + alarm[2], 0, digitPosY + 20);
		}
		g.drawString(
				Integer.toString(uur, 10) + " : "
						+ Integer.toString(minuut, 10) + " : "
						+ Integer.toString(seconde), digitPosX, digitPosY);
	}

	public void update() {
		tick();
		checkAlarm();
		repaint();
	}

	private void tick() {
		seconde = (seconde + 1) % 60;
		if (seconde == 0) {
			minuut = (minuut + 1) % 60;
			if (minuut == 0) {
				uur = (uur + 1) % 24;
			}
		}
	}

	private void checkAlarm() {
		if (uur == alarm[0] && minuut == alarm[1] && seconde == alarm[2]) {
			setAlarm(true);
		}
	}

	private void setAlarm(boolean b) {
		alarmSetOff = b;
	}

	public void setAlarmTimer(int[] alarm) {
		this.alarm = alarm;
	}
}